﻿namespace Resto.CostControl.Core
{
    using System;
    using System.Data;
    using System.IO;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

    /// <summary>
    /// 第三方组件NPOI的帮助类
    /// </summary>
    public class NPOIHelper
    {
        /// <summary>
        /// 读取excel，默认第一行的书签内容为表头
        /// </summary>
        /// <param name="strFileName">excel文档路径</param>
        /// <returns></returns>
        public static DataTable Import(string strFileName)
        {
            DataTable dt = new DataTable();

            IWorkbook hssfworkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            var sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            var headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                var cell = headerRow.GetCell(j);
                var comment = cell.CellComment;
                if (comment != null)
                {
                    var commentText = comment.String.ToString();
                    var names = commentText.Split(Environment.NewLine.ToCharArray());
                    foreach (var name in names)
                    {
                        var keys = name.Split(":：".ToCharArray());
                        if (keys.Length == 2)
                        {
                            if (keys[0] == "code") // 标识
                            {
                                dt.Columns.Add(keys[1]);
                            }
                            else if (keys[0] == "name") // 名称
                            {

                            }
                        }
                    }
                }
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                var row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null && j < dataRow.Table.Columns.Count)
                        dataRow[j] = row.GetCell(j).ToString();
                }

                dt.Rows.Add(dataRow);
            }
            return dt;
        }
    }
}
